package edu.csl.study.springboot.config;

import edu.csl.study.springboot.common.interceptor.ExceptionPreHandleInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;
import java.io.File;
import java.util.HashSet;
import java.util.Set;


/**
 * Web配置文件,有如下设置：
 * <ul>
 * <li>设置允许GET、POST、OPTIONS请求(设置OPTIONS是为了支持跨域请求)
 * </ul>
 *
 * @author zhouxianli
 *
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {


    @Autowired
    private ExceptionPreHandleInterceptor exceptionPreHandleInterceptor;

//    @Autowired
//    private LogInterceptor logInterceptor;
    /**
     * 不经过需要授权的路径
     */
	public final static Set<String> permitUlrPatterns = new HashSet<>();

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		  // 全局异常处理 前置处理拦截器
		  registry.addInterceptor(exceptionPreHandleInterceptor).addPathPatterns("/**");
	}

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
				// .allowedOrigins("http://localhost:8080")
				// .allowedHeaders("header1", "header2", "header3")
				// .exposedHeaders("header1", "header2")
				// .allowCredentials(false)
				// .maxAge(3600)
				.allowedMethods("GET", "POST", "OPTIONS");
	}


	@Bean
	public MultipartConfigElement multipartConfigElement() {
		MultipartConfigFactory factory = new MultipartConfigFactory();
		String url = ClassUtils.getDefaultClassLoader().getResource("").getPath();
		File tmpFile = new File(url+"/tempdir");
		if (!tmpFile.exists()) {
			tmpFile.mkdirs();
		}
		factory.setLocation(url+"/tempdir");
		return factory.createMultipartConfig();
	}


}
